import { HttpEvent, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { Observable } from 'rxjs';
import { HttpService } from './http.service';

/** 文件操作 */
@Injectable({ providedIn: 'root' })
export class FileService {

	constructor(private http: HttpService) { }

	/** 在新窗口中打开 */
	openInTab(blob: Blob): void {
		const url = window.URL.createObjectURL(blob);
		window.open(url, '_blank');
	}

	/** 保存文件 */
	saveAsFile(blob: Blob, fileName: string): void {
		const link = document.createElement('a');
		link.setAttribute('href', window.URL.createObjectURL(blob));
		link.setAttribute('download', fileName);
		link.style.visibility = 'hidden';
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	}

	uploadProgress(url: string, formData: FormData, params: NzSafeAny): Observable<HttpEvent<NzSafeAny>> {
		return this.http
			.post<NzSafeAny>(url, formData, params, {
				observe: 'events',
				reportProgress: true
			});
	}

	upload(url: string, formData: FormData, params: NzSafeAny): Observable<NzSafeAny> {
		return this.http.post<NzSafeAny>(url, formData, params);
	}

	download(url: string): Observable<Blob> {
		return this.http.get(url, null, { responseType: 'blob', headers: new HttpHeaders().append('Content-Type', 'application/json') });
	}

	downloads(url: string, params: NzSafeAny): Observable<Blob> {
		return this.http.get(url, params, { responseType: 'blob', headers: new HttpHeaders().append('Content-Type', 'application/json') });
	}
}
